<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24" :sm="24" :lg="12">
        <el-input v-model="fileNames" readonly></el-input>
      </el-col>
      <el-col :span="24" :sm="24" :lg="12">
        <el-button type="primary" icon="el-icon-upload" @click="dialogVisible=!dialogVisible">附件管理</el-button>
      </el-col>
    </el-row>
    <vxe-modal resize mask-closable width="30%" height="70%" v-model="dialogVisible">
      <template slot="title">
        <span>附件列表</span>
      </template>
      <template>
        <el-scrollbar class="scrollbar-handle">
          <el-dialog
            :close-on-click-modal="false"
            :visible.sync="dialogVisibleImg"
            :title="ImgName"
            append-to-body
          >
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
          <el-upload
            class="uploadShow"
            :accept="accept"
            :action="upload"
            :data="datas()"
            :headers="headers()"
            :multiple="multiple"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            list-type="picture"
            :before-remove="beforeRemove"
            :file-list.sync="fileList"
          >
            <el-button
              v-if="!isRead"
              type="primary"
              icon="el-icon-upload"
              style="float: left;"
            >新增附件</el-button>
          </el-upload>
        </el-scrollbar>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { AnnexesFile } from "@/api";
import util from "@/util";
export default {
  props: {
    //多文件上传
    multiple: {
      type: Boolean,
      default: true
    },
    //能否上传
    isRead: {
      type: Boolean,
      default: false
    },
    //能否删除
    removable: {
      type: Boolean,
      default: true
    },
    //上传类型
    accept: {
      type: String,
      default: ""
    },
    //文件夹Id
    folderId: {
      type: String,
      default: util.newGUID()
    }
  },
  data() {
    return {
      dialogVisible: false,
      defaultfileList: [], //原始数据（数据库数据）
      fileList: [], // 渲染数据
      dialogVisibleImg: false,
      dialogImageUrl: "",
      ImgName: ""
    };
  },
  computed: {
    ...mapGetters(["root","token"]),
    //上传路径
    upload() {
      return this.root + `adminApi/AnnexesFile/Upload`;
    },
    //文件名
    fileNames() {
      const res = [];
      this.fileList.forEach(c => {
        res.push(c.name);
      });
      return res.join(",");
    }
  },
  //folderId变动时初始化文件列表
  watch: {
    folderId(e) {
      this.findLists();
    }
  },
  //初始化文件列表
  created() {
    this.findLists();
  },
  methods: {
    //获取文件列表
    findLists() {
      //重置原始数据与渲染数据
      this.fileList = Object.assign([], []);
      this.defaultfileList = Object.assign([], []);
      //请求列表
      AnnexesFile.GetAnnexesFileList(this.folderId).then(res => {
        res.forEach(l => {
          const obj = {
            name: l.B_FileName,
            url:
              this.root + `adminApi/AnnexesFile/DownAnnexesFile?fileId=` + l.B_Id
          };
          this.fileList.push(obj);
        });
        //保存原始数据
        this.defaultfileList = Object.assign([], res);
      });
    },
    //Http请求Headers
    headers() {
      const object = {
        Authorization: "Bearer " + this.token
      };
      return object;
    },
    //上传附带参数
    datas() {
      const param = {
        //文件Id
        folderId: this.folderId
      };
      return param;
    },
    //上传成功后
    handleSuccess(res, file, fileList) {
      this.defaultfileList.push(res.data);
      this.fileList = Object.assign([], fileList);
      this.$emit("update:fileList", fileList);
    },
    //删除附件
    beforeRemove(file, fileList) {
      if (this.removable) {
        this.$confirm(`确定移除 ${file.name}？`, "提示", {
          type: "warning"
        })
          .then(() => {
            //获取索引
            const index = this.fileList.findIndex(el => {
              return file.uid === el.uid;
            });
            //请求删除
            AnnexesFile.DeleteAnnexesFile(
              this.defaultfileList[index].B_Id
            ).then(res => {
              //同步原始数据与渲染数据
              this.defaultfileList.splice(index, 1);
              this.fileList.splice(index, 1);
            });
          })
          .catch(() => {
            this.$message.info("已取消操作");
          });
      }
      return false;
    },
    //点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      const arr = ["gif", "jpg", "jpeg", "png", "PNG", "JPG", "GIF"];
      const s = arr.filter(el => {
        return file.name.includes(el);
      });
      if (s.length) {
        //如果是图片格式，则弹窗显示
        this.dialogImageUrl = file.url;
        this.dialogVisibleImg = true;
      } else {
        //否则下载
        window.open(file.url);
      }
    }
  }
};
</script>

<style scoped>
.uploadShow {
}
</style>
